package com.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.mapper.EmpExprMapper;
import com.study.mapper.EmpMapper;
import com.study.pojo.Emp;
import com.study.pojo.EmpExpr;
import com.study.pojo.EmpQueryParam;
import com.study.pojo.PageResult;
import com.study.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;
    @Autowired
    EmpExprMapper empExprMapper;
    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        //使用PageHelper插件改造
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());
        List<Emp> empList = empMapper.list(empQueryParam);
        Page<Emp> p = (Page<Emp>)empList;
        //List<Emp> empList = empMapper.list(start, pageSize);
        return new PageResult<> (p.getTotal(),p.getResult());
    }

    @Override
    public void save(Emp emp) {
        //添加员工信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
        //保存员工基本信息
        //保存员工工作经历信息
        //1.获取主键
        Integer empId = emp.getId();
        //2.获取员工之前是否有工作经历列表
        List<EmpExpr> exprList = emp.getExprList();
        //如果非空设置主键
        if(!CollectionUtils.isEmpty(exprList)){
            //如果非空，设置先前获取的主键为部门ID
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    }
}
